package com.qd.security;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import java.security.SecureRandom;

import lombok.extern.slf4j.Slf4j;

/**
 * @author taomk
 * @version 1.0
 * @since 2014/9/22 14:33
 */
@Slf4j
public final class AESUtils {

	private static final String SEC_TYPE = "AES";

	private AESUtils() {
	}

	public static byte[] encrypt(String strIn, String password) {
		return encrypt(strIn.getBytes(), password);
	}

	/**
	 * 加密
	 *
	 * @param arrB     需要加密的内容
	 * @param password 加密密码
	 * @return
	 */
	public static byte[] encrypt(byte[] arrB, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance(SEC_TYPE);
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, SEC_TYPE);
			Cipher cipher = Cipher.getInstance(SEC_TYPE);// 创建密码器
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(arrB);
			return result; // 加密
		} catch (Exception e) {
			log.error("error exception", e);
		}
		return null;
	}

	public static byte[] decrypt(String strIn, String password) {
		return decrypt(strIn.getBytes(), password);
	}

	/**
	 * 解密
	 *
	 * @param arrB     待解密内容
	 * @param password 解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] arrB, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance(SEC_TYPE);
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, SEC_TYPE);
			Cipher cipher = Cipher.getInstance(SEC_TYPE);// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(arrB);
			return result; // 加密
		} catch (Exception e) {
			log.error("error exception", e);
		}
		return null;
	}
}